package com.yuyou.train.user.controller;

import com.yuyou.train.util.tool.BeanUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;  import org.slf4j.LoggerFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yuyou.train.service.api.user.dto.UserPageDTO;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.entity.UserImport;
import com.yuyou.train.user.service.IUserDataConfigService;
import com.yuyou.train.user.service.IUserDynamicService;
import com.yuyou.train.user.service.IUserImportService;
import com.yuyou.train.user.service.IUserService;
import com.yuyou.train.user.vo.req.ReqUpdateUser;
import com.yuyou.train.user.vo.req.ReqUserPage;
import com.yuyou.train.user.vo.req.UserExcel;
import com.yuyou.train.user.vo.resp.RespHomepageOfTeacher;
import com.yuyou.train.user.vo.resp.RespTeacherInfo;
import com.yuyou.train.user.vo.resp.RespUserDetail;
import com.yuyou.train.user.vo.resp.RespUserDynamic;
import com.yuyou.train.user.vo.resp.RespUserInfo;
import com.yuyou.train.util.bean.LoginRedisObj;
import com.yuyou.train.util.bean.PageParams;
import com.yuyou.train.util.bean.Pagination;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.bean.ReturnResult;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.user.UserEnums;
import com.yuyou.train.util.tool.DateUtil;
import com.yuyou.train.util.tool.DefindBeanUtils;
import com.yuyou.train.util.tool.Webs;

@Validated
@RestController
@RequestMapping(value="/api/user")
public class UserController extends BaseController{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private IUserService userService;

	@Autowired
	private IUserDataConfigService userDataConfigService;
	
	@Autowired
	private IUserImportService userImportService;

	@Autowired
	private IUserDynamicService userDynamicService;

	@ApiOperation(value="更新用户资料（前台）")
	@RequestMapping(value="/updateUser" ,method=RequestMethod.POST)
	public ReturnResult<ResBoolSimpleInfo<User>> updateUser(@Validated @ModelAttribute ReqUpdateUser reqUpdateUser,HttpServletRequest request) throws Exception{
		LoginRedisObj loginObj = getUserObj(request);
		User user = new User();
		DefindBeanUtils.copyProperties(reqUpdateUser, user);
		user.setId(loginObj.getUserId());
		user.setRegisterTime(DateUtil.now());
		user.setType(loginObj.getType());

		ResBoolSimpleInfo<User> res=userService.updateUser(user, reqUpdateUser.getSubjectList(), reqUpdateUser.getSectionList(), reqUpdateUser.getTagList());		
		return ReturnResult.success(res);
	}


	@ApiOperation(value="获取用户详情(前台)")
	@RequestMapping(value="/userInfo" ,method=RequestMethod.POST)
	public ReturnResult<RespUserInfo> userInfo(HttpServletRequest request) throws Exception{
		LoginRedisObj loginObj = getUserObj(request);
		RespUserInfo res = userService.userInfo(loginObj.getUserId());
		return ReturnResult.success(res);
	}
	
	
	@ApiOperation(value="根据用户ID获取用户详情")
	@RequestMapping(value="/detailUser" ,method=RequestMethod.POST)
	public ReturnResult<RespUserDetail> detailUser(@NotEmpty (message="用户ID不能为空") @RequestParam(value="id") String id){
		RespUserDetail res = userService.detailUser(id);
		return ReturnResult.success(res);
	}


	@ApiOperation(value=" 获取导师信息")
	@RequestMapping(value="/detailTeacher" ,method=RequestMethod.POST)
	public ReturnResult<RespTeacherInfo> detailTeacher(@RequestParam(value="studentId", required = false) String studentId,
													   @NotEmpty (message="teacherId 不能为空") @RequestParam(value="teacherId") String teacherId,
													   HttpServletRequest request){
		if(null == studentId){
			LoginRedisObj loginObj = this.getUserObj(request);
			studentId = loginObj.getUserId();
		}
		RespTeacherInfo respTeacherInfo = userService.detailTeacher(studentId, teacherId);
		return ReturnResult.success(respTeacherInfo);
	}

	
	@ApiOperation(value="批量更新用户状态")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "ids", value = "用户ID列表（多个逗号分隔）", paramType="query", required = true),
		@ApiImplicitParam(name = "status", value = "账号状态：0：正常，1：冻结", paramType="query",required = true)}
		)
	@RequestMapping(value="/batchUpdSta" ,method=RequestMethod.POST)
	public ReturnResult<ResBoolSimpleInfo> batchUpdSta(
			@NotEmpty (message="用户ID列表(ids)不能为空") @RequestParam(value="ids") List<String> ids,
			@NotEmpty (message="状态不能为空") @RequestParam(value="status") String status,
			HttpServletRequest request){
		ResBoolSimpleInfo res=userService.batchUpdSta(ids, status);
		return ReturnResult.success(res);
	}


	
	@ApiOperation(value="删除用户")
	@ApiImplicitParam(name = "id", value = "用户ID", paramType="query", required = true)
	@RequestMapping(value="/delUser" ,method=RequestMethod.POST)
	public ReturnResult<ResBoolSimpleInfo> delUser(@NotEmpty (message="用户ID不能为空") @RequestParam(value="id") String id){
		ResBoolSimpleInfo res=userService.delUser(id);
		return ReturnResult.success(res);
	}	


	@ApiOperation(value="用户列表分页")
	@RequestMapping(value="/findUserPage" ,method=RequestMethod.POST)
	public ReturnResult<UserPageDTO> findUserPage(
			HttpServletRequest request,
			@Validated @ModelAttribute PageParams pageParams,
			@Validated @ModelAttribute ReqUserPage reqUserPage){
		LoginRedisObj obj=getUserObj(request);	
		String loginUserId=obj.getUserId();
		Map<String, Object> conditions=new HashMap<String, Object>();
		conditions.put("isDel",CommEnums.isDel.no.getValue() );
		conditions.put("type", reqUserPage.getType());
		conditions.put("subjectId", reqUserPage.getSubjectId());
		conditions.put("serText", reqUserPage.getSerText());
		conditions.put("classId", reqUserPage.getClassId());
		conditions.put("sectionId", reqUserPage.getSectionId());		
		conditions.put("learnStatus", reqUserPage.getLearnStatus());
		conditions.put("attr", reqUserPage.getAttr());	
		conditions.put("status", reqUserPage.getStatus());
		
		conditions.put("teacherId", loginUserId);	
		if(BooleanUtils.toBoolean(reqUserPage.getShowMyStu())){
			conditions.put("showMyStu", loginUserId);
		}	
		conditions.put("regTimeStart", reqUserPage.getRegTimeStart());
		conditions.put("regTimeEnd", reqUserPage.getRegTimeEnd());
		//数据权限
		if(obj.getTag().equals(LoginRedisObj.tagEnum.portal.getValue()) 
				&& obj.getType().equals(UserEnums.type.teacher.getValue())){
			conditions.put("showMyClass", loginUserId);
		}
		Pagination<UserPageDTO> queryPgn = new Pagination<UserPageDTO>();
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total =userService.findUserPageCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total>0){
			queryPgn.setTotal(total);
			List<UserPageDTO> list=userService.findUserPageList(queryPgn);
			for(UserPageDTO dto:list){
				if(!StringUtils.isEmpty(dto.getParentId())&&dto.getParentId().equals(loginUserId)&& !dto.getLearnStatus().equals(UserEnums.learnStatus.trainning.getValue())){
					dto.setNeedKeyWord(true);
				}
				if(!StringUtils.isEmpty(dto.getParentId())&&dto.getParentId().equals(loginUserId)){
					dto.setShowMyStu(true);
				}				
			}
			queryPgn.setList(list);
		}		
		return ReturnResult.success(queryPgn);
	}


	@ApiOperation(value="导师天团分页(前台)")
	@RequestMapping(value="/findTeacherPage" ,method=RequestMethod.POST)
	public ReturnResult<Pagination<UserPageDTO>> findUserPage(@Validated @ModelAttribute PageParams pageParams,
												  HttpServletRequest request){

		LoginRedisObj loginObj = this.getUserObj(request);
		User user = userService.selectByPrimaryKey(loginObj.getUserId());

		Map<String, Object> conditions=new HashMap<>();
		conditions.put("type", UserEnums.type.teacher.getValue());
		conditions.put("classId", user.getClassId());
		Pagination<UserPageDTO> queryPgn = new Pagination<UserPageDTO>();
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = userService.findTeacherPageCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			queryPgn.setTotal(total);
			List<UserPageDTO> list = userService.findTeacherPageList(queryPgn);
			queryPgn.setList(list);

			// 判断是否是我导师
			for(UserPageDTO oneUser : list){
				if(oneUser.getId().equals(user.getParentId())){
					oneUser.setIsMyTutor(CommEnums.isOrNot.yes.getValue());
				}else{
					oneUser.setIsMyTutor(CommEnums.isOrNot.no.getValue());
				}
			}
		}

		return ReturnResult.success(queryPgn);
	}


	@ApiOperation(value="导师个人主页(前台)")
	@RequestMapping(value="/homepageOfTeacher" ,method=RequestMethod.POST)
	public ReturnResult<RespHomepageOfTeacher> homepageOfTeacher(HttpServletRequest request){

		LoginRedisObj loginObj = this.getUserObj(request);
		User user = userService.selectByPrimaryKey(loginObj.getUserId());
		ResBoolSimpleInfo<RespHomepageOfTeacher> res = userService.homepageOfTeacher(user.getId());

		return ReturnResult.success(res);
	}



	@ApiOperation("导入用户信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "type", value = "导入的用户类型，0 : 学员, 1:导师", paramType="query", required = true),
			@ApiImplicitParam(name = "file", value = "文件", paramType="query",required = true)}
	)
	@RequestMapping(value = "/userImport", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
	public ReturnResult<UserImport> userImport( String type, MultipartFile file) throws Exception {

		InputStream inputStream = file.getInputStream();
		ImportParams params = new ImportParams();
		List<UserExcel> userExcelList = ExcelImportUtil.importExcel(inputStream, UserExcel.class, params);

		UserImport userImport = userService.saveUserImport(userExcelList, type);
		return ReturnResult.success(userImport);
	}


	@ApiOperation("上次导入情况")
	@RequestMapping(value = "/lastInfoImport", method = {RequestMethod.GET,RequestMethod.POST})
	public ReturnResult<UserImport> lastInfoImport(@NotBlank(message="type不能为空") @RequestParam(value="type") String type) {

		UserImport userImport = userImportService.findLatestUserImportByType(type);
		return ReturnResult.success(userImport);
	}

	@ApiOperation("导出失败信息")
	@RequestMapping(value = "/failedInfoExport", method = {RequestMethod.GET,RequestMethod.POST})
	public ReturnResult<Void> failedInfoExport(@NotBlank(message="type不能为空") @RequestParam(value="type") String type,
											   HttpServletRequest request, HttpServletResponse response) {

		UserImport userImport = userImportService.findLatestUserImportByType(type);
		List<UserExcel> userExcelList = JSONObject.parseObject(userImport.getContent(), new TypeReference<List<UserExcel>>() {});
		XSSFWorkbook excel = userService.failedInfoOfUserImport(userExcelList);

		Webs.writeExcel(request, response, excel , "导入失败信息表");
		return ReturnResult.success("ok");
	}


	@ApiOperation(value="课程、作业动态(前台)")
	@RequestMapping(value="/userDynamicPage",method = RequestMethod.POST)
	public ReturnResult<Pagination<RespUserDynamic>> userDynamicPage(@Validated @ModelAttribute PageParams pageParams,
													  @NotBlank(message="type不能为空") @ApiParam(value = "类型：01：课程，02：作业, 03：感想") @RequestParam(value="type") String type,
													  HttpServletRequest request){
		LoginRedisObj loginObj = this.getUserObj(request);
		User user = userService.selectByPrimaryKey(loginObj.getUserId());

		Map<String, Object> conditions = new HashMap<>();
		Pagination<RespUserDynamic> queryPgn = new Pagination<>();

		conditions.put("classId", user.getClassId());
		// 课程的时候全查
		if(!"01".equals(type)){
			conditions.put("type", type);
		}
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = userDynamicService.findUserDynamicPageCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			queryPgn.setTotal(total);
			List<RespUserDynamic> list = userDynamicService.findUserDynamicPage(queryPgn);
			queryPgn.setList(list);
		}
		return ReturnResult.success(queryPgn);
	}
	
	
	@ApiOperation("填写结课寄语")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "endWord", value = "结课寄语", paramType="query", required = true),
		@ApiImplicitParam(name = "userId", value = "用户主键", paramType="query",required = true)}
			)
	@RequestMapping(value = "/endWord", method = {RequestMethod.GET,RequestMethod.POST})
	public ReturnResult<UserImport> endWord( HttpServletRequest request,
			@NotBlank(message="userId不能为空") @RequestParam(value="userId") String userId,
			@NotBlank(message="endWord不能为空") @RequestParam(value="endWord") String endWord) throws Exception {	
		
		LoginRedisObj loginObj = this.getUserObj(request);
		
		ResBoolSimpleInfo<String> res=userService.endWord(userId,loginObj.getUserId(),endWord);		
		return ReturnResult.success(res);
	}
}
